<template>
  <div class="user-management-page">
    <!-- 页面标题 -->
    <div class="page-header">
              <h1 class="page-title">
          <el-icon><UserIcon /></el-icon>
          管理中心
        </h1>
      <div class="page-actions">
        <button class="btn btn-outline" @click="exportUserData">
          <el-icon><Download /></el-icon>
          导出数据
        </button>
        <button class="btn btn-success" @click="goToUserDataManagement">
          <el-icon><Setting /></el-icon>
          修改用户数据
        </button>
        <button class="btn btn-primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </button>

      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">总用户数</div>
            <div class="stat-value">{{ userStats.totalUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <el-icon><TrendCharts /></el-icon>
                {{ userStats.totalUsersGrowth }}%
              </span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-blue">
            <el-icon><UserIcon /></el-icon>
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">活跃用户</div>
            <div class="stat-value">{{ userStats.activeUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <el-icon><TrendCharts /></el-icon>
                {{ userStats.activeUsersGrowth }}%
              </span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-green">
            <el-icon><UserFilled /></el-icon>
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">VIP用户</div>
            <div class="stat-value">{{ userStats.vipUsers }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <el-icon><TrendCharts /></el-icon>
                {{ userStats.vipUsersGrowth }}%
              </span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-orange">
            <el-icon><StarFilled /></el-icon>
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-label">今日新增</div>
            <div class="stat-value">{{ userStats.newUsersToday }}</div>
            <div class="stat-trend">
              <span class="trend-up">
                <el-icon><TrendCharts /></el-icon>
                {{ userStats.newUsersTodayGrowth }}%
              </span>
              <span class="trend-label">较昨日</span>
            </div>
          </div>
          <div class="stat-icon stat-icon-purple">
            <el-icon><UserIcon /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <!-- 第一行：筛选条件 -->
      <div class="filter-row">
        <div class="filter-group">
          <label>用户状态：</label>
          <select v-model="filters.status" class="filter-select" @change="applyFilters">
            <option value="">全部状态</option>
            <option value="active">正常</option>
            <option value="banned">封禁</option>
            <option value="suspended">暂停</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>VIP状态：</label>
          <select v-model="filters.vipStatus" class="filter-select" @change="applyFilters">
            <option value="">全部</option>
            <option value="monthly">月度VIP</option>
            <option value="yearly">年度VIP</option>
            <option value="none">普通用户</option>
          </select>
        </div>

        <div class="filter-group">
          <label>用户角色：</label>
          <select v-model="filters.role" class="filter-select" @change="applyFilters">
            <option value="">全部角色</option>
            <option value="user">普通用户</option>
            <option value="moderator">版主</option>
            <option value="admin">管理员</option>
          </select>
        </div>

        <div class="filter-group">
          <label>余额范围：</label>
          <div class="balance-filter">
            <input 
              v-model.number="filters.balanceMin" 
              type="number" 
              placeholder="最小"
              class="balance-input"
              @input="applyFilters"
            >
            <span>-</span>
            <input 
              v-model.number="filters.balanceMax" 
              type="number" 
              placeholder="最大"
              class="balance-input"
              @input="applyFilters"
            >
          </div>
        </div>
      </div>
      
      <!-- 第二行：搜索和操作 -->
      <div class="filter-row">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索用户名、邮箱、ID..."
            class="search-input"
            @keyup.enter="performSearch"
          >
          <button class="search-btn" @click="performSearch" :disabled="loading">
            <el-icon><Search /></el-icon>
          </button>
        </div>
        <button class="btn btn-outline" @click="resetFilters">
          <el-icon><Filter /></el-icon>
          重置筛选
        </button>
        <div class="quick-stats">
          <span class="stats-item">
            <strong>当前显示:</strong> {{ paginatedUsers.length }} 人
          </span>
          <span class="stats-item">
            <strong>筛选结果:</strong> {{ totalUsersFromAPI }} 人
          </span>
        </div>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedUsers.length > 0" class="bulk-actions-bar">
      <div class="bulk-info">
        <span>已选择 {{ selectedUsers.length }} 个用户</span>
        <button class="clear-selection" @click="selectedUsers = []">
          <el-icon><Close /></el-icon>
          清除选择
        </button>
      </div>
      <div class="bulk-buttons">
        <button class="btn btn-warning" @click="bulkUpdateVip">
          <el-icon><StarFilled /></el-icon>
          批量VIP
        </button>
        <button class="btn btn-success" @click="bulkRecharge">
          <el-icon><CreditCard /></el-icon>
          批量充值
        </button>
        <button class="btn btn-danger" @click="bulkBan">
          <el-icon><Lock /></el-icon>
          批量封禁
        </button>
      </div>
    </div>

    <!-- 用户数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>用户信息</th>
            <th>等级/角色</th>
            <th>VIP状态</th>
            <th>钱包余额</th>
            <th>账号状态</th>
            <th>注册时间</th>
            <th>最后登录</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUsers" :key="user.id" class="table-row">
            <td>
              <input 
                type="checkbox" 
                :value="user.id"
                v-model="selectedUsers"
                class="user-checkbox"
              >
              <div class="user-info">
                <div class="user-avatar">
                  <img :src="user.avatar || '/default-avatar.svg'" :alt="user.nickname" @error="handleImageError">
                  <div v-if="user.status === 'banned'" class="status-overlay banned">
                    <el-icon><Lock /></el-icon>
                  </div>
                  <div v-else-if="user.vipStatus !== 'none'" class="status-overlay vip">
                    <el-icon><StarFilled /></el-icon>
                  </div>
                </div>
                <div class="user-details">
                  <div class="user-name">{{ user.nickname || user.username || user.email }}</div>
                  <div class="user-email">{{ user.email }}</div>
                  <div class="user-id">ID: {{ user.id }}</div>
                </div>
              </div>
            </td>
            <td>
              <div class="level-info">
                <span class="level-badge" :class="`level-${user.level}`">
                  Lv.{{ user.level }}
                </span>
                <div class="role-tag" :class="user.role">{{ getRoleText(user.role || 'user') }}</div>
              </div>
            </td>
            <td>
              <div class="vip-status">
                <span v-if="user.vipStatus !== 'none'" class="vip-badge">
                  <el-icon><StarFilled /></el-icon>
                  {{ getVipText(user.vipStatus || 'none') }}
                </span>
                <span v-else class="normal-user">普通用户</span>
              </div>
            </td>
            <td>
                              <div class="wallet-amount">{{ (user.coins || user.balance || 0).toLocaleString() }} 书币</div>
            </td>
            <td>
              <span class="status-badge" :class="user.status">
                {{ getStatusText(user.status || 'active') }}
              </span>
            </td>
            <td>
              <div class="date-info">
                <div>{{ formatDate(user.createdAt || '') }}</div>
                <div class="time-detail">{{ formatTime(user.createdAt || '') }}</div>
              </div>
            </td>
            <td>
              <div class="date-info">
                <div v-if="user.lastLoginTime">{{ formatDate(user.lastLoginTime) }}</div>
                <div v-else class="never-login">从未登录</div>
                <div v-if="user.lastLoginTime" class="time-detail">{{ formatTime(user.lastLoginTime) }}</div>
              </div>
            </td>
            <td>
              <div class="action-buttons">
                <div class="action-row">
                  <!-- 操作按钮已移除 -->
                </div>

                
                <!-- 快捷操作下拉选择器 -->
                <div class="action-selects">
                  <select class="action-select vip-select" @change="handleVipChange(user, $event)" :value="getVipSelectValue(user.vipStatus || 'none')">
                    <option value="">👑 VIP</option>
                    <option value="none">普通</option>
                    <option value="monthly">月VIP</option>
                    <option value="yearly">年VIP</option>
                  </select>
                  <select class="action-select wallet-select" @change="handleWalletChange(user, $event)" value="">
                    <option value="">💰 钱包</option>
                    <option value="recharge">充值</option>
                    <option value="deduct">扣费</option>
                    <option value="set">设置</option>
                  </select>
                  <select class="action-select status-select" @change="handleStatusChange(user, $event)" :value="user.status">
                    <option value="">🔒 状态</option>
                    <option value="active">正常</option>
                    <option value="banned">封禁</option>
                  </select>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页 -->
      <div class="pagination">
        <div class="pagination-info">
          显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalUsersFromAPI) }} 条，
          共 {{ totalUsersFromAPI }} 条
        </div>
        <div class="pagination-controls">
          <div class="page-size-selector">
            <label>每页显示：</label>
            <select v-model="pageSize" @change="handlePageSizeChange">
              <option :value="10">10条</option>
              <option :value="20">20条</option>
              <option :value="50">50条</option>
              <option :value="100">100条</option>
            </select>
          </div>
          
          <div class="page-navigation">
            <button 
              class="page-btn" 
              @click="goToPage(1)" 
              :disabled="currentPage === 1"
              title="首页"
            >
              <el-icon><DArrowLeft /></el-icon>
            </button>
            <button 
              class="page-btn" 
              @click="goToPage(currentPage - 1)" 
              :disabled="currentPage === 1"
              title="上一页"
            >
              <el-icon><ArrowLeft /></el-icon>
            </button>
            
            <!-- 页码显示 -->
            <div class="page-numbers">
              <template v-for="page in visiblePages" :key="page">
                <button 
                  v-if="page !== '...'"
                  class="page-btn page-number"
                  :class="{ active: page === currentPage }"
                  @click="goToPage(page as number)"
                >
                  {{ page }}
                </button>
                <span v-else class="page-ellipsis">...</span>
              </template>
            </div>
            
            <button 
              class="page-btn" 
              @click="goToPage(currentPage + 1)" 
              :disabled="currentPage === totalPages"
              title="下一页"
            >
              <el-icon><ArrowRight /></el-icon>
            </button>
            <button 
              class="page-btn" 
              @click="goToPage(totalPages)" 
              :disabled="currentPage === totalPages"
              title="末页"
            >
              <el-icon><DArrowRight /></el-icon>
            </button>
          </div>
          
          <div class="page-jump">
            <span>跳转到</span>
            <input 
              type="number" 
              v-model="jumpToPage" 
              @keyup.enter="handlePageJump"
              :min="1" 
              :max="totalPages"
              placeholder="页码"
            >
            <button class="jump-btn" @click="handlePageJump">Go</button>
          </div>
        </div>
      </div>
    </div>
  </div>



  <!-- 用户详情对话框 -->
  <div v-if="showDetailDialog && selectedUser" class="modal-overlay" @click="closeDetailDialog">
    <div class="modal-content user-detail-modal" @click.stop>
      <div class="modal-header">
        <h3>用户详情 - {{ selectedUser.nickname || selectedUser.email }}</h3>
        <button class="close-btn" @click="closeDetailDialog">
          <el-icon><Close /></el-icon>
        </button>
      </div>
      <div class="modal-body">
        <div class="detail-sections">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">用户ID:</span>
                <span class="value">{{ selectedUser.id }}</span>
              </div>
              <div class="detail-item">
                <span class="label">昵称:</span>
                <span class="value">{{ selectedUser.nickname || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ selectedUser.email }}</span>
              </div>
              <div class="detail-item">
                <span class="label">等级:</span>
                <span class="value">Lv.{{ selectedUser.level || 1 }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>账户状态</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">角色:</span>
                <span class="value">{{ getRoleText(selectedUser.role || 'user') }}</span>
              </div>
              <div class="detail-item">
                <span class="label">状态:</span>
                <span class="value">{{ getStatusText(selectedUser.status || 'active') }}</span>
              </div>
              <div class="detail-item">
                <span class="label">VIP状态:</span>
                <span class="value">{{ getVipText(selectedUser.vipStatus || 'none') }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>钱包信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">余额:</span>
                <span class="value">{{ (selectedUser.balance || 0).toLocaleString() }} 书币</span>
              </div>
            </div>
          </div>
          
          <div class="detail-section">
            <h4>时间信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">注册时间:</span>
                <span class="value">{{ formatDate(selectedUser.createdAt || '') }}</span>
              </div>
              <div class="detail-item">
                <span class="label">最后登录:</span>
                <span class="value">{{ selectedUser.lastLoginTime ? formatDate(selectedUser.lastLoginTime) : '从未登录' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 编辑用户对话框 -->
  <div v-if="showUserDialog && selectedUser" class="modal-overlay" @click="closeUserDialog">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>编辑用户 - {{ selectedUser.nickname || selectedUser.email }}</h3>
        <button class="close-btn" @click="closeUserDialog">
          <el-icon><Close /></el-icon>
        </button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="saveUser">
          <div class="form-row">
            <div class="form-group">
              <label>昵称</label>
              <input v-model="userForm.nickname" type="text" class="form-input" placeholder="请输入昵称">
            </div>
            <div class="form-group">
              <label>等级</label>
              <input v-model.number="userForm.level" type="number" class="form-input" min="1">
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>角色</label>
              <select v-model="userForm.role" class="form-select">
                <option value="user">普通用户</option>
                <option value="vip">VIP用户</option>
                <option value="admin">管理员</option>
              </select>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="userForm.status" class="form-select">
                <option value="active">正常</option>
                <option value="banned">封禁</option>
              </select>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>VIP状态</label>
              <select v-model="userForm.vipStatus" class="form-select">
                <option value="none">普通用户</option>
                <option value="monthly">月度VIP</option>
                <option value="yearly">年度VIP</option>
              </select>
            </div>
            <div class="form-group">
              <label>余额（书币）</label>
              <input v-model.number="userForm.balance" type="number" class="form-input" min="0">
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closeUserDialog">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- 重置密码对话框 -->
  <div v-if="showPasswordDialog && selectedUser" class="modal-overlay" @click="closePasswordDialog">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>重置密码 - {{ selectedUser.nickname || selectedUser.email }}</h3>
        <button class="close-btn" @click="closePasswordDialog">
          <el-icon><Close /></el-icon>
        </button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="resetPassword">
          <div class="form-group">
            <label>新密码 *</label>
            <input 
              v-model="passwordForm.newPassword" 
              type="password" 
              required 
              minlength="6"
              class="form-input"
              placeholder="请输入新密码"
            >
          </div>
          <div class="form-group">
            <label>确认新密码 *</label>
            <input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              required 
              minlength="6"
              class="form-input"
              placeholder="请再次输入新密码"
            >
          </div>
          <div class="form-group">
            <label>操作原因</label>
            <textarea 
              v-model="passwordForm.reason" 
              class="form-textarea"
              placeholder="请说明重置密码的原因..."
              rows="3"
            ></textarea>
          </div>
          <div class="form-actions">
            <button type="button" class="btn btn-outline" @click="closePasswordDialog">取消</button>
            <button type="submit" class="btn btn-primary">重置密码</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- 用户详情对话框 -->
  <div v-if="showDetailDialog && selectedUser" class="modal-overlay" @click="closeDetailDialog">
    <div class="modal-content user-detail-modal" @click.stop>
      <div class="modal-header">
        <h3>用户详情 - {{ selectedUser.nickname || selectedUser.email }}</h3>
        <button class="close-btn" @click="closeDetailDialog">
          <el-icon><Close /></el-icon>
        </button>
      </div>
      <div class="modal-body">
        <div class="detail-sections">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h4>👤 基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">用户ID:</span>
                <span class="value">{{ selectedUser.id }}</span>
              </div>
              <div class="detail-item">
                <span class="label">用户名:</span>
                <span class="value">{{ selectedUser.nickname || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ selectedUser.email }}</span>
              </div>
              <div class="detail-item">
                <span class="label">头像:</span>
                <span class="value">{{ selectedUser.avatar || '无' }}</span>
              </div>
            </div>
          </div>

          <!-- 账户状态 -->
          <div class="detail-section">
            <h4>👑 账户状态</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">角色:</span>
                <span class="value">{{ getRoleText(selectedUser.role || 'user') }}</span>
              </div>
              <div class="detail-item">
                <span class="label">状态:</span>
                <span class="value">{{ getStatusText(selectedUser.status || 'active') }}</span>
              </div>
              <div class="detail-item">
                <span class="label">等级:</span>
                <span class="value">Lv.{{ selectedUser.level || 1 }}</span>
              </div>
              <div class="detail-item">
                <span class="label">权限:</span>
                <span class="value">{{ selectedUser.role === 'admin' ? '管理员' : '普通用户' }}</span>
              </div>
            </div>
          </div>

          <!-- VIP信息 -->
          <div class="detail-section">
            <h4>💎 VIP信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">VIP状态:</span>
                <span class="value">{{ getVipText(selectedUser.vipStatus || 'none') }}</span>
              </div>
              <div class="detail-item" v-if="selectedUser.vipExpireDate">
                <span class="label">到期时间:</span>
                <span class="value">{{ formatDate(selectedUser.vipExpireDate) }}</span>
              </div>
            </div>
          </div>

          <!-- 钱包信息 -->
          <div class="detail-section">
            <h4>💰 钱包信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">余额:</span>
                <span class="value">{{ (selectedUser.coins || selectedUser.balance || 0).toLocaleString() }} 书币</span>
              </div>
            </div>
          </div>

          <!-- 时间信息 -->
          <div class="detail-section">
            <h4>🕒 时间信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">注册时间:</span>
                <span class="value">{{ selectedUser.createdAt ? `${formatDate(selectedUser.createdAt)} ${formatTime(selectedUser.createdAt)}` : '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">最后登录:</span>
                <span class="value">{{ selectedUser.lastLoginTime ? `${formatDate(selectedUser.lastLoginTime)} ${formatTime(selectedUser.lastLoginTime)}` : '从未登录' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>


</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { User } from '@/types'
import { UserManagementDBAPI } from '@/api/userManagementDB'
import { useUserStore } from '@/stores/user'
import { 
  DArrowLeft, 
  DArrowRight, 
  ArrowLeft, 
  ArrowRight,
  Close,
  Search,
  Filter,
  Download,
  Setting,
  Refresh,
  Plus,
  StarFilled,
  CreditCard,
  Lock,
  User as UserIcon,
  UserFilled,
  TrendCharts,
  Upload
} from '@element-plus/icons-vue'

// Router
const router = useRouter()

// User Store
const userStore = useUserStore()

// 响应式数据
const users = ref<User[]>([])
const loading = ref(false)
const searchQuery = ref('')

// 筛选器
const filters = ref({
  status: '',
  vipStatus: '',
  role: '',
  balanceMin: 0,
  balanceMax: 0
})

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalUsersFromAPI = ref(0)
const jumpToPage = ref<number | null>(null)

// 批量选择
const selectedUsers = ref<string[]>([])

// 统计数据
const userStats = ref({
  totalUsers: 0,
  totalUsersGrowth: 0,
  activeUsers: 0,
  activeUsersGrowth: 0,
  vipUsers: 0,
  vipUsersGrowth: 0,
  newUsersToday: 0,
  newUsersTodayGrowth: 0
})



// 计算属性

// 使用服务端分页，所以paginatedUsers就是users
const paginatedUsers = computed(() => users.value)

const totalPages = computed(() => 
  Math.ceil(totalUsersFromAPI.value / pageSize.value) || 1
)

// 显示的页码列表
const visiblePages = computed(() => {
  const pages: (number | string)[] = []
  const total = totalPages.value
  const current = currentPage.value
  
  if (total <= 7) {
    // 总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于7，显示省略号
    if (current <= 4) {
      // 当前页在前4页
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后4页
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }
  
  return pages
})

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const result = await UserManagementDBAPI.getAllUsers(currentPage.value, pageSize.value, searchQuery.value, filters.value)
    users.value = result.users
    totalUsersFromAPI.value = result.total
    // 更新统计数据
    const stats = await UserManagementDBAPI.getUserStats()
    console.log('📊 获取到的统计数据:', stats)
    userStats.value = {
      totalUsers: stats.totalUsers || 0,
      totalUsersGrowth: stats.totalUsersGrowth || 0,
      activeUsers: stats.activeUsers || 0,
      activeUsersGrowth: stats.activeUsersGrowth || 0,
      vipUsers: stats.vipUsers || 0,
      vipUsersGrowth: stats.vipUsersGrowth || 0,
      newUsersToday: stats.newUsersToday || 0,
      newUsersTodayGrowth: stats.newUsersTodayGrowth || 0
    }
  } catch (error) {
    console.error('Failed to load users:', error)
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadUsers()
}

const resetFilters = () => {
  filters.value = {
    status: '',
    vipStatus: '',
    role: '',
    balanceMin: 0,
    balanceMax: 0
  }
  searchQuery.value = ''
  currentPage.value = 1
}

// 分页方法
const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const handlePageSizeChange = () => {
  currentPage.value = 1
  loadUsers()
}

const handlePageJump = () => {
  if (jumpToPage.value && jumpToPage.value >= 1 && jumpToPage.value <= totalPages.value) {
    goToPage(jumpToPage.value)
    jumpToPage.value = null
  }
}

const exportUserData = () => {
  // 导出用户数据为CSV
  const csvData = users.value.map(user => ({
    ID: user.id,
    用户名: user.nickname,
    邮箱: user.email,
    等级: user.level,
    VIP状态: getVipText(user.vipStatus || 'none'),
    余额: user.coins || user.balance || 0,
    状态: getStatusText(user.status || 'active'),
    注册时间: formatDate(user.createdAt || ''),
    最后登录: user.lastLoginTime ? formatDate(user.lastLoginTime) : '从未登录'
  }))
  
  const csv = [
    Object.keys(csvData[0]).join(','),
    ...csvData.map(row => Object.values(row).join(','))
  ].join('\n')
  
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `用户数据_${new Date().toISOString().split('T')[0]}.csv`
  link.click()
  alert('用户数据导出成功！')
}

const goToUserDataManagement = () => {
  router.push('/admin/user-data')
}

// 获取VIP状态对应的select值
const getVipSelectValue = (vipStatus: string) => {
  return vipStatus || ''
}

// VIP状态下拉框处理
const handleVipChange = async (user: User, event: Event) => {
  const target = event.target as HTMLSelectElement
  const newStatus = target.value as "monthly" | "yearly" | "none"
  
  if (newStatus && newStatus !== user.vipStatus) {
    const success = await UserManagementDBAPI.updateUser(user.id.toString(), { vipStatus: newStatus })
    if (success) {
      user.vipStatus = newStatus
      const statusText = getVipText(newStatus)
      alert(`VIP状态修改成功！\n新状态：${statusText}`)
    } else {
      alert('VIP状态修改失败，请重试！')
    }
  }
  
  // 重置选择器
  target.value = ''
}

// 钱包管理下拉框处理
const handleWalletChange = async (user: User, event: Event) => {
  const target = event.target as HTMLSelectElement
  const action = target.value
  
  if (action) {
    let amount: number
    const currentBalance = (user.coins || user.balance || 0).toLocaleString()
    
    if (action === 'set') {
      const newBalance = prompt(`当前余额：${currentBalance} 书币\n\n请输入新的余额：`)
      if (newBalance && !isNaN(Number(newBalance))) {
        amount = Number(newBalance)
        const success = await UserManagementDBAPI.updateUser(user.id.toString(), { balance: amount })
        if (success) {
          user.coins = amount
          user.balance = amount
          alert(`余额设置成功！\n新余额：${amount.toLocaleString()} 书币`)
        } else {
          alert('余额设置失败，请重试！')
        }
      }
    } else {
      const actionText = action === 'recharge' ? '充值' : '扣费'
      const amountStr = prompt(`当前余额：${currentBalance} 书币\n\n请输入${actionText}金额：`)
      if (amountStr && !isNaN(Number(amountStr))) {
        amount = Number(amountStr)
        const userBalance = user.coins || user.balance || 0
        const newBalance = action === 'recharge' ? userBalance + amount : userBalance - amount
        
        if (newBalance < 0) {
          alert('余额不足，无法扣费！')
          target.value = ''
          return
        }
        
        const success = await UserManagementDBAPI.updateUser(user.id.toString(), { balance: newBalance })
        if (success) {
          user.coins = newBalance
          user.balance = newBalance
          alert(`${actionText}成功！\n新余额：${newBalance.toLocaleString()} 书币`)
        } else {
          alert(`${actionText}失败，请重试！`)
        }
      }
    }
  }
  
  // 重置选择器
  target.value = ''
}

// 账号状态下拉框处理
const handleStatusChange = async (user: User, event: Event) => {
  const target = event.target as HTMLSelectElement
  const newStatus = target.value as "active" | "banned"
  
  if (newStatus && newStatus !== user.status) {
    const action = newStatus === 'banned' ? '封禁' : '解封'
    
    if (confirm(`确定要${action}用户 "${user.nickname || user.username || user.email}" 吗？`)) {
      const success = await UserManagementDBAPI.updateUser(user.id.toString(), { status: newStatus })
      if (success) {
        user.status = newStatus
        alert(`用户${action}成功！`)
      } else {
        alert(`用户${action}失败，请重试！`)
      }
    } else {
      // 如果取消操作，恢复原值
      target.value = user.status || 'active'
    }
  }
}

const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    user: '读者',
    admin: '管理员',
    moderator: '版主'
  }
  return roleMap[role] || role
}

const getVipText = (vipStatus: string) => {
  const vipMap: Record<string, string> = {
    monthly: '月度VIP',
    yearly: '年度VIP',
    none: '普通用户'
  }
  return vipMap[vipStatus] || vipStatus
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '正常',
    banned: '封禁',
    suspended: '暂停'
  }
  return statusMap[status] || status
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatTime = (dateString: string) => {
  return new Date(dateString).toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/default-avatar.svg'
}



// 执行搜索
const performSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 批量操作方法
const bulkUpdateVip = async () => {
  if (selectedUsers.value.length === 0) {
    alert('请先选择要批量操作的用户！')
    return
  }

  const newVipStatus = prompt('请输入新的VIP状态 (monthly, yearly, none):')
  if (!newVipStatus || !['monthly', 'yearly', 'none'].includes(newVipStatus)) {
    alert('请输入有效的VIP状态！')
    return
  }

  const confirmed = confirm(`确定要将选中的 ${selectedUsers.value.length} 个用户设置为 VIP 状态 "${getVipText(newVipStatus)}" 吗？`)
  if (!confirmed) return

  try {
    const vipStatusValue = newVipStatus as 'monthly' | 'yearly' | 'none'
    const success = await UserManagementDBAPI.batchUpdateUsers(selectedUsers.value, { vipStatus: vipStatusValue })
    if (success) {
      alert(`批量VIP状态更新成功！`)
      selectedUsers.value = []
      await loadUsers()
    } else {
      alert('批量VIP操作失败，请重试。')
    }
  } catch (error) {
    console.error('Bulk VIP update error:', error)
    alert('批量VIP操作失败，请检查网络。')
  }
}

const bulkRecharge = async () => {
  if (selectedUsers.value.length === 0) {
    alert('请先选择要批量操作的用户！')
    return
  }

  const amountStr = prompt('请输入要批量充值的金额 (例如: 1000):')
  if (!amountStr || isNaN(Number(amountStr))) {
    alert('请输入有效的充值金额！')
    return
  }
  const amount = Number(amountStr)

  const confirmed = confirm(`确定要将选中的 ${selectedUsers.value.length} 个用户余额增加 ${amount.toLocaleString()} 书币吗？`)
  if (!confirmed) return

  try {
    // 这里需要逐个更新用户余额，因为需要计算新余额
    let successCount = 0
    for (const userId of selectedUsers.value) {
      const user = users.value.find(u => u.id.toString() === userId)
      if (user) {
        const newBalance = (user.balance || 0) + amount
        const success = await UserManagementDBAPI.updateUser(userId, { balance: newBalance })
        if (success) successCount++
      }
    }
    
    if (successCount > 0) {
      alert(`成功为 ${successCount} 个用户充值 ${amount.toLocaleString()} 书币。`)
      selectedUsers.value = []
      await loadUsers()
    } else {
      alert('批量充值操作失败。')
    }
  } catch (error) {
    console.error('Bulk recharge error:', error)
    alert('批量充值操作失败，请检查网络。')
  }
}

const bulkBan = async () => {
  if (selectedUsers.value.length === 0) {
    alert('请先选择要批量操作的用户！')
    return
  }

  const confirmed = confirm(`确定要将选中的 ${selectedUsers.value.length} 个用户封禁吗？`)
  if (!confirmed) return

  try {
    const success = await UserManagementDBAPI.batchUpdateUsers(selectedUsers.value, { status: 'banned' })
    if (success) {
      alert(`批量封禁操作成功！`)
      selectedUsers.value = []
      await loadUsers()
    } else {
      alert('批量封禁操作失败，请重试。')
    }
  } catch (error) {
    console.error('Bulk ban error:', error)
    alert('批量封禁操作失败，请检查网络。')
  }
}

// 应用筛选器
const applyFilters = () => {
  currentPage.value = 1
  loadUsers()
}

// 弹窗状态
const showDetailDialog = ref(false)
const showPasswordDialog = ref(false)
const showUserDialog = ref(false)
const selectedUser = ref<User | null>(null)
const isEditing = ref(false)

// 表单数据
const userForm = ref({
  email: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  role: 'user' as User['role'],
  status: 'active' as User['status'],
  vipStatus: 'none' as User['vipStatus'],
  level: 1,
  balance: 0,
  avatar: ''
})

const passwordForm = ref({
  newPassword: '',
  confirmPassword: '',
  reason: ''
})



const closeUserDialog = () => {
  showUserDialog.value = false
  resetUserForm()
  selectedUser.value = null
}

const resetUserForm = () => {
  userForm.value = {
    email: '',
    nickname: '',
    password: '',
    confirmPassword: '',
    role: 'user',
    status: 'active',
    vipStatus: 'none',
    level: 1,
    balance: 0,
    avatar: ''
  }
}

const saveUser = async () => {
  if (userForm.value.password && userForm.value.password !== userForm.value.confirmPassword) {
    alert('两次输入的密码不一致！')
    return
  }

  try {
    if (isEditing.value && selectedUser.value) {
      // 编辑用户
      const success = await UserManagementDBAPI.updateUser(selectedUser.value.id.toString(), {
        nickname: userForm.value.nickname,
        role: userForm.value.role,
        status: userForm.value.status,
        vipStatus: userForm.value.vipStatus,
        level: userForm.value.level,
        balance: userForm.value.balance,
        avatar: userForm.value.avatar || undefined
      })
      
      if (success) {
        alert('用户信息更新成功！')
        await loadUsers()
        closeUserDialog()
      } else {
        alert('用户信息更新失败，请重试！')
      }
    }
  } catch (error) {
    console.error('Save user error:', error)
    alert('操作失败，请重试！')
  }
}



const closePasswordDialog = () => {
  showPasswordDialog.value = false
  selectedUser.value = null
}

const resetPassword = async () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    alert('两次输入的密码不一致！')
    return
  }

  if (!selectedUser.value) return

  try {
    const success = await UserManagementDBAPI.updateUser(selectedUser.value.id.toString(), {
      password: passwordForm.value.newPassword
    })

    if (success) {
      alert('密码重置成功！')
      closePasswordDialog()
    } else {
      alert('密码重置失败，请重试！')
    }
  } catch (error) {
    console.error('Reset password error:', error)
    alert('密码重置失败，请重试！')
  }
}



// 监听页面变化
watch(currentPage, () => {
  loadUsers()
})

// 监听搜索变化
watch(searchQuery, () => {
  currentPage.value = 1
  loadUsers()
})

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
/* 页面整体样式 */
.user-management-page {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, sans-serif;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.trend-up {
  display: flex;
  align-items: center;
  gap: 2px;
  color: #10b981;
  font-weight: 500;
}

.trend-label {
  color: #64748b;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon-blue {
  background: #dbeafe;
  color: #3b82f6;
}

.stat-icon-green {
  background: #d1fae5;
  color: #10b981;
}

.stat-icon-orange {
  background: #fed7aa;
  color: #f59e0b;
}

.stat-icon-purple {
  background: #e9d5ff;
  color: #8b5cf6;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #374151;
  white-space: nowrap;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background: white;
  min-width: 120px;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  padding: 8px 16px 8px 40px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  width: 300px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.operation-hint {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #6b7280;
  background: #f8fafc;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.operation-hint i {
  color: #3b82f6;
}

/* 筛选区域新增样式 */
.balance-filter {
  display: flex;
  align-items: center;
  gap: 8px;
}

.balance-input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 13px;
}

.search-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.search-btn:hover {
  background-color: #f3f4f6;
  color: #374151;
}

.search-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quick-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 13px;
  color: #6b7280;
  background: #f8fafc;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #3b82f6;
}

.stats-item {
  display: flex;
  gap: 4px;
}

/* 表格样式 */
.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  background: #f8fafc;
  padding: 16px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  border-bottom: 1px solid #e5e7eb;
}

.data-table td {
  padding: 16px;
  border-bottom: 1px solid #f3f4f6;
  vertical-align: middle;
}

.table-row:hover {
  background-color: #f8fafc;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  position: relative;
  width: 48px;
  height: 48px;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
}

.user-email {
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 2px;
}

.user-id {
  font-size: 12px;
  color: #9ca3af;
}

/* 等级和角色 */
.level-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.level-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  text-align: center;
  min-width: 50px;
}

.level-1 { background: #dbeafe; color: #1e40af; }
.level-2 { background: #dcfce7; color: #166534; }
.level-3 { background: #fef3c7; color: #92400e; }
.level-4 { background: #fce7f3; color: #be185d; }
.level-5 { background: #ede9fe; color: #7c2d12; }

.role-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.role-tag.user { background: #f3f4f6; color: #374151; }
.role-tag.admin { background: #fecaca; color: #dc2626; }
.role-tag.moderator { background: #dbeafe; color: #1e40af; }

/* VIP状态 */
.vip-status {
  display: flex;
  align-items: center;
}

.vip-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.normal-user {
  color: #6b7280;
  font-size: 14px;
}

/* 钱包余额 */
.wallet-amount {
  font-weight: 600;
  color: #059669;
}

/* 状态标签 */
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.status-badge.active {
  background: #dcfce7;
  color: #166534;
}

.status-badge.banned {
  background: #fecaca;
  color: #dc2626;
}

.status-badge.suspended {
  background: #fef3c7;
  color: #92400e;
}

/* 日期信息 */
.date-info {
  font-size: 14px;
}

.time-detail {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.never-login {
  color: #9ca3af;
  font-style: italic;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.action-row {
  display: flex;
  gap: 6px;
}

/* 操作按钮 */
.action-btn {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  transition: all 0.2s;
  min-height: 28px;
  flex: 1;
}

.action-btn.detail {
  background: #3b82f6;
  color: white;
}

.action-btn.detail:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.action-btn.edit {
  background: #10b981;
  color: white;
}

.action-btn.edit:hover {
  background: #059669;
  transform: translateY(-1px);
}

.action-btn.password {
  background: #f59e0b;
  color: white;
}

.action-btn.password:hover {
  background: #d97706;
  transform: translateY(-1px);
}

.action-btn.view {
  background: #6366f1;
  color: white;
}

.action-btn.view:hover {
  background: #4f46e5;
  transform: translateY(-1px);
}

.action-btn.danger {
  background: #ef4444;
  color: white;
}

.action-btn.danger:hover {
  background: #dc2626;
  transform: translateY(-1px);
}

.btn-placeholder {
  flex: 1;
  min-height: 28px;
}

.action-btn.btn-info {
  background: #3b82f6;
  color: white;
}

.action-btn.btn-info:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.action-btn.btn-danger {
  background: #ef4444;
  color: white;
}

.action-btn.btn-danger:hover {
  background: #dc2626;
  transform: translateY(-1px);
}

/* 操作下拉框 */
.action-selects {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-select {
  padding: 4px 8px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background: white;
  color: #374151;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-height: 28px;
}

.action-select:hover {
  border-color: #d1d5db;
  background: #f9fafb;
}

.action-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 1px #3b82f6;
}

.vip-select {
  border-color: #fbbf24;
  background: #fefbf0;
}

.vip-select:hover {
  border-color: #f59e0b;
  background: #fef3c7;
}

.wallet-select {
  border-color: #10b981;
  background: #f0fdf4;
}

.wallet-select:hover {
  border-color: #059669;
  background: #dcfce7;
}

.status-select {
  border-color: #ef4444;
  background: #fef2f2;
}

.status-select:hover {
  border-color: #dc2626;
  background: #fee2e2;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #f8fafc;
}

.pagination-info {
  font-size: 14px;
  color: #6b7280;
  white-space: nowrap;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #64748b;
}

.page-size-selector select {
  padding: 4px 8px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background: white;
  font-size: 14px;
}

.page-navigation {
  display: flex;
  align-items: center;
  gap: 4px;
}

.page-numbers {
  display: flex;
  align-items: center;
  gap: 2px;
  margin: 0 8px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  min-width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-btn:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.page-btn:disabled {
  background: #f9fafb;
  color: #d1d5db;
  cursor: not-allowed;
}

.page-btn.page-number {
  min-width: 36px;
}

.page-btn.page-number.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.page-ellipsis {
  padding: 8px 4px;
  color: #9ca3af;
  font-size: 14px;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #64748b;
}

.page-jump input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  text-align: center;
  font-size: 14px;
}

.jump-btn {
  padding: 4px 12px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.jump-btn:hover {
  background: #2563eb;
}

@media (max-width: 768px) {
  .pagination {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .pagination-controls {
    flex-direction: column;
    gap: 12px;
  }
  
  .page-navigation {
    justify-content: center;
  }
  
  .page-jump {
    justify-content: center;
  }
  
  .page-size-selector {
    justify-content: center;
  }

  /* 筛选区域响应式 */
  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .filter-group {
    justify-content: space-between;
    width: 100%;
  }

  .filter-select {
    min-width: 150px;
  }

  .search-input {
    width: 100%;
  }

  .quick-stats {
    order: -1;
    margin-bottom: 12px;
  }
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.btn-primary {
  background: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background: #2563eb;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-success:hover {
  background: #059669;
}

.btn-outline {
  background: white;
  color: #6b7280;
  border: 1px solid #d1d5db;
}

.btn-outline:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

/* 按钮颜色 */
.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

/* 上传小说对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-height: 90vh;
  overflow-y: auto;
}



/* 批量操作栏样式 */
.bulk-actions-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
  animation: slideDown 0.3s ease-out;
}

.bulk-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 500;
}

.clear-selection {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.clear-selection:hover {
  background: rgba(255, 255, 255, 0.3);
}

.bulk-buttons {
  display: flex;
  gap: 12px;
}

.bulk-buttons .btn {
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
  color: white;
}

.bulk-buttons .btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* 用户表格新增样式 */
.user-checkbox {
  margin-right: 12px;
  transform: scale(1.1);
}

.user-avatar {
  position: relative;
  width: 48px;
  height: 48px;
}

.status-overlay {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.status-overlay.banned {
  background: #dc2626;
  color: white;
}

.status-overlay.vip {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
}

@keyframes slideDown {
  from {
    transform: translateY(-10px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .pagination {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .pagination-controls {
    flex-direction: column;
    gap: 12px;
  }
  
  .page-navigation {
    justify-content: center;
  }
  
  .page-jump {
    justify-content: center;
  }
  
  .page-size-selector {
    justify-content: center;
  }

  .bulk-actions-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .bulk-info {
    justify-content: center;
  }
  
  .bulk-buttons {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .quick-stats {
    flex-direction: row;
    justify-content: space-between;
  }
  
  .balance-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .balance-filter span {
    text-align: center;
    margin: 4px 0;
  }
}

/* 对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.modal-content {
  background: white;
  border-radius: 12px;
  max-width: 600px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.2s ease-out;
}

.user-detail-modal {
  max-width: 800px;
}

@keyframes slideIn {
  from { 
    transform: translateY(-20px); 
    opacity: 0; 
  }
  to { 
    transform: translateY(0); 
    opacity: 1; 
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.modal-body {
  padding: 20px;
}

/* 详情对话框样式 */
.detail-sections {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #1f2937;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.detail-item .label {
  font-weight: 500;
  color: #6b7280;
}

.detail-item .value {
  font-weight: 600;
  color: #1f2937;
  text-align: right;
}

/* 表单样式 */
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

/* 密码显示样式 */
.password-display {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.password-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.password-field .form-input {
  flex: 1;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.warning-text {
  background: #fef3c7;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #f59e0b;
}

.warning-text p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #92400e;
}

.warning-text p:last-child {
  margin-bottom: 0;
}
</style> 